package com.zzcy.bt_print_plugin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zzcy.bt_print_plugin.view.MyTableTextView_Right;
import com.zzcy.bt_print_plugin.view.UnderlineTextView;

import java.text.DecimalFormat;

public class PrintActivity extends Activity {
    private String TAG = PrintActivity.class.getSimpleName();
    private LinearLayout mainLinerLayout;
    private RelativeLayout rlTopBar;
    private RelativeLayout rlBg;
    private RelativeLayout rlStatus;
    private String printJsonObject;
    private ImageView ivBack;
    private ImageView ivStatus;
    private TextView tvStatus;
    private int jsonType;
    private static BitmapCallback callback;

    // 静态方法启动页面并传递回调
    public static void startDrawBitmap(Context context, String printJsonObject, int jsonType, BitmapCallback bitmapCallback) {
        callback = bitmapCallback;
        Intent intent = new Intent(context, PrintActivity.class);
        intent.putExtra("printJsonObject", printJsonObject);
        intent.putExtra("jsonType", jsonType);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 获取当前Activity的Window对象
        Window window = getWindow();
        // 获取WindowManager.LayoutParams对象
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        // 将flags属性设置为FLAG_TRANSLUCENT_STATUS，表示状态栏透明
        layoutParams.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        // 设置状态栏的背景颜色为白色
        window.setStatusBarColor(Color.TRANSPARENT);
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;// 屏幕宽度（像素）
        layoutParams.width = (int) (width * 0.5);
//        Log.e("OkHttp", "onSuccess屏幕的宽度的值:" + width + "==" + ((int) (width * 0.5)));
        // 更新Window的参数
        window.setAttributes(layoutParams);
        setContentView(R.layout.activity_print);
        rlTopBar = findViewById(R.id.rlPrintTopBar);
        mainLinerLayout = findViewById(R.id.llPrint);
        rlBg = findViewById(R.id.rlBg);
        ivBack = findViewById(R.id.ivBack);
        tvStatus = findViewById(R.id.tvStatus);
        rlStatus = findViewById(R.id.rlStatus);
        ivStatus = findViewById(R.id.ivStatus);
        initView();
        setOnClick();

        printJsonObject = getIntent().getExtras().getString("printJsonObject");
        jsonType = getIntent().getExtras().getInt("jsonType");
        Log.e(TAG, "打印数据：" + printJsonObject + ":" + jsonType);

        startPrint();
    }

    private void initView() {
        int actionBarHeight = getActionBarHeight();
        int statusBarHeight = getStatusBarHeight();
        if (statusBarHeight == 0) {
            statusBarHeight = 50;
        }
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, statusBarHeight, 0, 0);
        layoutParams.height = actionBarHeight;
        rlTopBar.setLayoutParams(layoutParams);
    }

    private void setOnClick() {
        ivBack.setOnClickListener(v -> {
            finish();
        });
    }

    private void startPrint() {
        mainLinerLayout.removeAllViews();
//        String printJsonObject = jsonType == 1 ? oneJson : jsonType == 2 ? twoJson : threeJson;
        JSONObject jsonObject = JSONObject.parseObject(printJsonObject);
        if (jsonType == 1) {
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            String title = jsonObject.getString("title");
            String date = jsonObject.getString("date");
            String name = jsonObject.getString("name");
            String dateCycle = jsonObject.getString("dateCycle");

            LinearLayout titleLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.title_layout, null);
            TextView tvTitle = titleLinearLayout.findViewById(R.id.tvTitle);
            TextView tvDay = titleLinearLayout.findViewById(R.id.tvDay);
            TextView tvName = titleLinearLayout.findViewById(R.id.tvName);
            TextView tvDateCycle = titleLinearLayout.findViewById(R.id.tvDateCycle);
            tvDay.setText(date);
            tvName.setText(name);
            tvDateCycle.setText(dateCycle);
            tvTitle.setText(title);
            mainLinerLayout.addView(titleLinearLayout);

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                String chName = json.getString("ChName");
                String enName = json.getString("EnName");

                LinearLayout tabLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.table_layout, null);
                MyTableTextView_Right textRight = (MyTableTextView_Right) tabLinearLayout.findViewById(R.id.list_1_2);
                TextView tvEnglish = tabLinearLayout.findViewById(R.id.tvEnglish);

                tvEnglish.setText(enName);
                textRight.setText(chName);
                mainLinerLayout.addView(tabLinearLayout);

                if ((i + 1) % 5 == 0 && i != jsonArray.size() - 1) {
                    // 在每次添加第5个单词之前的位置添加空线，但不要在最后一个单词之后添加空线
                    LinearLayout viewLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.view_layout, null);
                    mainLinerLayout.addView(viewLinearLayout);
                }
            }
        } else if (jsonType == 2) {
            String title = jsonObject.getString("title");
            JSONArray jsonArray = jsonObject.getJSONArray("data");

            LinearLayout titleLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.title_layout_common, null);
            TextView tvTitle = titleLinearLayout.findViewById(R.id.tvTitle);
            tvTitle.setText(title);
            mainLinerLayout.addView(titleLinearLayout);

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                String chName = json.getString("ChName");
                String enName = json.getString("EnName");
                //添加单词
                LinearLayout tabLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.table_layout_two, null);
                TextView tvEn = tabLinearLayout.findViewById(R.id.tvEn);
                TextView tvCh = tabLinearLayout.findViewById(R.id.tvCh);
                //赋值打印数据
                tvEn.setText(enName);
                tvCh.setText(chName);
                mainLinerLayout.addView(tabLinearLayout);
                if ((i + 1) % 5 == 0 && i != jsonArray.size() - 1) {
                    // 在每次添加第5个单词之前的位置添加空线，但不要在最后一个单词之后添加空线
                    LinearLayout viewLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.view_layout, null);
                    mainLinerLayout.addView(viewLinearLayout);
                }
            }
        } else if (jsonType == 3) {
            String title = jsonObject.getString("title");
            String subheading = jsonObject.getString("subheading");
            Integer type = jsonObject.getInteger("type");
            JSONArray jsonArray = jsonObject.getJSONArray("data");

            LinearLayout titleLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.title_layout_common_three, null);
            TextView tvTitle = titleLinearLayout.findViewById(R.id.tvTitle);
            TextView tvSubheading = titleLinearLayout.findViewById(R.id.tvSubheading);
            tvTitle.setText(title);
            tvSubheading.setText(subheading);
            mainLinerLayout.addView(titleLinearLayout);

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                String chName = json.getString("ChName");
                String enName = json.getString("EnName");
                //添加单词
                LinearLayout tabLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.table_layout_three, null);
                TextView tvEn = tabLinearLayout.findViewById(R.id.tvEn);
                TextView tvCh = tabLinearLayout.findViewById(R.id.tvCh);
                UnderlineTextView tvExtendCh = tabLinearLayout.findViewById(R.id.tvExtendCh);
                UnderlineTextView tvExtendEn = tabLinearLayout.findViewById(R.id.tvExtendEn);
                View viewLine = tabLinearLayout.findViewById(R.id.viewLine);
                if (type == 1) {
                    //中英文
                    tvEn.setTextColor(Color.parseColor("#000000"));
                    tvCh.setTextColor(Color.parseColor("#000000"));
                    tvEn.setText(enName);
                    tvCh.setVisibility(View.GONE);
                    tvExtendCh.setText(chName);
                    tvExtendEn.setVisibility(View.GONE);
                    viewLine.setVisibility(View.GONE);
                } else if (type == 2) {
                    //中文
                    tvCh.setTextColor(Color.parseColor("#000000"));
                    tvCh.setText(chName);
                    tvEn.setVisibility(View.GONE);
                    tvExtendEn.setText("");
                    tvExtendCh.setVisibility(View.GONE);
                    viewLine.setVisibility(View.GONE);
                } else if (type == 3) {
                    //英文
                    tvEn.setTextColor(Color.parseColor("#000000"));
                    tvEn.setText(enName);
                    tvCh.setVisibility(View.GONE);
                    tvExtendCh.setText("");
                    tvExtendEn.setVisibility(View.GONE);
                    viewLine.setVisibility(View.GONE);
                }
//                if (!TextUtils.isEmpty(enName) && !TextUtils.isEmpty(chName)) {
//                    tvEn.setText(enName);
//                    tvCh.setText(chName);
//                } else if (!TextUtils.isEmpty(enName) && TextUtils.isEmpty(chName)) {
//                    //只有英文，没有中文
//                    tvEn.setText(enName);
//                } else if (TextUtils.isEmpty(enName) && !TextUtils.isEmpty(chName)) {
//                    tvEn.setText(chName);
//                }
                mainLinerLayout.addView(tabLinearLayout);
            }
        }
        //绘制完界面之后需要延迟进行打印，否则打印出来是空白的
        rlTopBar.postDelayed(() -> {
            try {
                Bitmap bmp = loadBitmapFromView(mainLinerLayout);

                bmp = bitmapZoom(bmp, 80);
                if (callback != null) {
                    callback.onBitmapDrawn(bmp);
                    finish();
                }
            } catch (Exception e) {
                BTModule.printFailFunc();
                Log.e("OkHttp", "onSuccess 打印报错: " + e.getMessage());
            }
        }, 2 * 1000);
    }

    public static Bitmap loadBitmapFromView(View v) {
        if (v == null) {
            return null;
        }
        Bitmap screenshot;
        Log.e("OkHttp", "onSuccess:获取屏幕的宽高 " + v.getWidth() + "==" + v.getHeight());
        screenshot = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(screenshot);
        canvas.translate(-v.getScrollX(), -v.getScrollY());//我们在用滑动View获得它的Bitmap时候，获得的是整个View的区域（包括隐藏的），如果想得到当前区域，需要重新定位到当前可显示的区域
        canvas.drawColor(Color.WHITE);
        v.draw(canvas);// 将 view 画到画布上
        return screenshot;
    }

    static DecimalFormat df = new DecimalFormat("0.00");

    public static Bitmap bitmapZoom(Bitmap mBitmap1, int paperWidth) {
        df = new DecimalFormat("0.00");
        Bitmap mBitmap = mBitmap1;
        // 根据纸张宽度设置目标宽度
        int width = paperWidth == 80 ? 576 : 384;
        if (mBitmap.getWidth() >= width) {
            float c = Float.valueOf(df.format((float) mBitmap.getWidth()
                    / width));
            int newHight = Integer.parseInt(new DecimalFormat("0")
                    .format(mBitmap.getHeight() / c));
            mBitmap = zoomImg(mBitmap, width, newHight);
        } else {
            float c = Float.valueOf(df.format((float) width
                    / mBitmap.getWidth()));
            int newHight1 = Integer.parseInt(new DecimalFormat("0")
                    .format(c * mBitmap.getHeight()));
            mBitmap = zoomImg(mBitmap, width, newHight1);
        }
        return mBitmap;
    }

    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                true);
        return newbm;
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    private int getStatusBarHeight() {
        Resources resources = getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    public int getActionBarHeight() {
        TypedValue typedValue = new TypedValue();
        int actionBarHeight = 0;
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValue, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(typedValue.data, getResources().getDisplayMetrics());
        }
        return actionBarHeight;
    }


    String oneJson = "{\n" +
            "    \"title\":\"智海马私人订制抗遗忘\",\n" +
            "\"date\":\"智海马私人订制抗遗忘\",\n" +
            "\"name\":\"智海马私人订制抗遗忘\",\n" +
            "\"dateCycle\":\"智海马私人订制抗遗忘测试换行测试换行\",\n" +
            "    \"type\":1,\n" +
            "    \"data\":[\n" +
            "        {\n" +
            "            \"ChName\":\"猫1\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫2\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫3\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫4\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫5\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫10\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    String twoJson = "{\n" +
            "    \"title\":\"智海马私人订制抗遗忘\",\n" +
            "    \"data\":[\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
//        String threeJson = "{\n" +
//            "    \"title\":\"智海马私人订制抗遗忘\",\n" +
//            "\"subheading\":\"副标题\",\n" +
//            "    \"type\":3,\n" +
//            "    \"data\":[\n" +
//            "        {\n" +
//            "            \"ChName\":\"扩展这些刻板印象对人们的影响是很大的。比如，一个穿着钉\",\n" +
//            "            \"EnName\":\"These stereotypes have a strong influence on people. For example\"\n" +
//            "        },{\n" +
//            "            \"ChName\":\"扩展这些刻板印象对人们的影响是很大的。比如，一个穿着钉\",\n" +
//            "            \"EnName\":\"These stereotypes have a strong influence on people. For example\"\n" +
//            "        }\n" +
//            "    ]\n" +
//            "}";
    String threeJson = "{\n" +
            "    \"title\": \"智海马私人订制\",\n" +
            "    \"type\": 3,\n" +
            "    \"subheading\": \"Work hard\",\n" +
            "    \"data\": \"[{\\\"ChName\\\":\\\"亲爱的同学们,\\\",\\\"EnName\\\":\\\"Dear students,\\\"},{\\\"ChName\\\":\\\"早上好/下午好/晚上好!\\\",\\\"EnName\\\":\\\"Good morning/afternoon/evening!\\\"},{\\\"ChName\\\":\\\"今天，我想和你们谈谈努力工作和尽力而为的重要性\\\",\\\"EnName\\\":\\\"Today, I want to talk to you about the importance of working hard and trying our best.\\\"},{\\\"ChName\\\":\\\"我们都知道，生活并不总是容易的\\\",\\\"EnName\\\":\\\"As we all know, life is not always easy.\\\"},{\\\"ChName\\\":\\\"一路上会有挑战和困难，但只要努力，我们就能战胜它们，实现我们的目标。\\\",\\\"EnName\\\":\\\"There will be challenges and difficulties along the way, but with hard work, we can beat them and achieve our goals.\\\"},{\\\"ChName\\\":\\\"让我们从“努力”这个词开始\\\",\\\"EnName\\\":\\\"Let's start by talking about the word \\\\\\\"effort.\\\\\\\"\\\"},{\\\"ChName\\\":\\\"努力意味着尽我们最大的努力，付出我们的一切。\\\",\\\"EnName\\\":\\\"Effort means trying our hardest and giving our all.\\\"},{\\\"ChName\\\":\\\"它是关于督促自己做到最好，即使遇到困难也不放弃。\\\",\\\"EnName\\\":\\\"It is about pushing ourselves to do our best and not giving up even when things get tough.\\\"},{\\\"ChName\\\":\\\"我们付出努力时，我们可以完成伟大的事情。\\\",\\\"EnName\\\":\\\"When we put in the effort, we can accomplish great things.\\\"},{\\\"ChName\\\":\\\"想象一下，一个学生有很多作业要做。\\\",\\\"EnName\\\":\\\"Imagine a student who has a lot of homework to do.\\\"},{\\\"ChName\\\":\\\"看起来可能很多，但只要努力，他们就能完成作业，在学习中取得好成绩。\\\",\\\"EnName\\\":\\\"It may seem like a lot, but with effort, they can complete their assignments and do well in their studies.\\\"},{\\\"ChName\\\":\\\"这一切都是关于保持专注，明智地管理我们的时间，不要分心。\\\",\\\"EnName\\\":\\\"It is all about staying focused, managing our time wisely, and not getting distracted.\\\"},{\\\"ChName\\\":\\\"取得成功的另一个重要因素是毅力。\\\",\\\"EnName\\\":\\\"Another important factor in achieving success is perseverance.\\\"},{\\\"ChName\\\":\\\"毅力意味着不放弃，坚持承诺，即使遇到挑战。\\\",\\\"EnName\\\":\\\"Perseverance means not giving up and staying committed, even when things are challenging.\\\"},{\\\"ChName\\\":\\\"它是关于当事情看起来很困难时，要有继续前进的决心\\\",\\\"EnName\\\":\\\"It is about having the determination to keep going when things seem difficult.\\\"},{\\\"ChName\\\":\\\"让我们以一个学生准备比赛为例。\\\",\\\"EnName\\\":\\\"Let's take the example of a student preparing for a competition.\\\"},{\\\"ChName\\\":\\\"他们可能面临激烈的竞争，有时会感到气馁。\\\",\\\"EnName\\\":\\\"They may face tough competition and feel discouraged at times.\\\"},{\\\"ChName\\\":\\\"然而，如果他们继续努力，继续练习和提高他们的技能，他们就能在比赛中取得成功。\\\",\\\"EnName\\\":\\\"However, if they keep trying and continue to practice and improve their skills, they can succeed in the competition.\\\"},{\\\"ChName\\\":\\\"毅力是达到目标的关键。\\\",\\\"EnName\\\":\\\"Perseverance is the key to reaching our goals.\\\"},{\\\"ChName\\\":\\\"此外，有一个积极的态度和相信自己是至关重要的。\\\",\\\"EnName\\\":\\\"Furthermore, it is crucial to have a positive attitude and believe in ourselves.\\\"},{\\\"ChName\\\":\\\"我们不应该让恐惧或自我怀疑阻碍我们前进。\\\",\\\"EnName\\\":\\\"We should not let fear or self-doubt hold us back.\\\"},{\\\"ChName\\\":\\\"相反，我们应该拥抱挑战，把它们视为成长和学习的机会。\\\",\\\"EnName\\\":\\\"Instead, we should embrace challenges and see them as opportunities for growth and learning.\\\"},{\\\"ChName\\\":\\\"记住，成功需要时间和努力。\\\",\\\"EnName\\\":\\\"Remember, it takes time and hard work to achieve success.\\\"},{\\\"ChName\\\":\\\"但只要有决心和努力，我们就能充分发挥我们的潜力，实现我们的梦想。\\\",\\\"EnName\\\":\\\"But with determination and effort, we can reach our full potential and achieve our dreams.\\\"},{\\\"ChName\\\":\\\"总之，我想鼓励你们所有人都要重视努力工作，永远不要停止努力。\\\",\\\"EnName\\\":\\\"In conclusion, I want to encourage all of you to value hard work and never stop trying your best.\\\"},{\\\"ChName\\\":\\\"有了努力、毅力和积极的态度，你就能克服任何障碍，实现你的目标。\\\",\\\"EnName\\\":\\\"With effort, perseverance, and a positive attitude, you can overcome any obstacle and achieve your goals.\\\"},{\\\"ChName\\\":\\\"所以，让我们都努力工作，让我们的梦想成真。\\\",\\\"EnName\\\":\\\"So, let's all work hard and make our dreams come true.\\\"},{\\\"ChName\\\":\\\"谢谢您的关注，祝您生活顺心如意!\\\",\\\"EnName\\\":\\\"Thank you for your attention, and I wish you all the best in your life.\\\"},{\\\"ChName\\\":\\\"真诚地,\\\",\\\"EnName\\\":\\\"Sincerely,\\\"}]\"\n" +
            "}";
}